<?php
namespace app\backend\controller;

class StaffApply extends Backend {
	
	public function index() {
		
		$view = \think\View::instance();
		$request = \think\Request::instance();
		
		$where = array();
		$condition = array();
		$condition['realname'] = $request->get('realname', '');
		if(0 < mb_strlen($condition['realname'], 'utf8')){
			$where['staff_apply.realname'] = array('like', '%%'.$condition['realname'].'%%');
		};
		$condition['result'] = $request->get('result', '0');
		if((0 < mb_strlen($condition['result'], 'utf8')) && settype($condition['result'], 'integer')){
			$where['staff_apply.result'] = $condition['result'];
		};
		$view->assign('condition', $condition);
		
		$field = array(
			'`staff_apply`.*',
		);
		$apply_select = \app\common\model\StaffApplyModel::field($field)
			->where($where)->order('staff_apply.id DESC')->paginate(10, false, array('query'=>$condition));
		$view->assign('page', $apply_select->render());
		
		$apply_list = array();
		foreach($apply_select as $StaffApplyModel){
			$apply = $StaffApplyModel->toArray();
			$apply['result_name'] = $StaffApplyModel->getResultName();
			$apply_list[] = $apply;
		};
		$view->assign('data_list', $apply_list);
		
		$view->assign('result', \app\common\model\StaffApplyModel::$result);
		
		unset($where, $condition, $field, $apply_select, $StaffApplyModel);
		return $view->fetch();
		
	}
	
	public function show_detail() {
		
		$view = \think\View::instance();
		$request = \think\Request::instance();
		
		$apply_id = $request->get('id', '');
		if(!is_string($apply_id) || (1 !== preg_match('/^[0-9]{1,10}$/', $apply_id))){
			throw new \think\Exception('参数校验失败');
		};
			
		$StaffApplyModel = \app\common\model\StaffApplyModel::get($apply_id);
		if(null === $StaffApplyModel){
			throw new \think\Exception('目标未找到');
		};
			
		if($request->isAjax()){
			
			if(0 !== $StaffApplyModel->result){
				return $this->disposeJson(1, '该申请已经被处理，请刷新列表后重试');
			};
			
			$parameter = $request->post();
			switch($parameter['action']){
				
				// 移除地区
				case 'remove_region' :
					
					$judge_1 = array_key_exists('key', $parameter) && is_integer($parameter['key']) && in_array($parameter['key'], array(0, 1, 2));
					if(!$judge_1){
						return $this->disposeJson(1, '参数校验失败');
					};
					
					$apply_region_id = explode(',', $StaffApplyModel->region_id);
					$apply_region_name = explode(',', $StaffApplyModel->region_name);
					if(!array_key_exists($parameter['key'], $apply_region_id) || !array_key_exists($parameter['key'], $apply_region_name)){
						return $this->disposeJson(1, '目标不存在不能移除');
					};
					
					unset($apply_region_id[$parameter['key']], $apply_region_name[$parameter['key']]);
					$apply_region_id = array_values($apply_region_id);
					$apply_region_name = array_values($apply_region_name);
					
					$StaffApplyModel->region_id = implode(',', $apply_region_id);
					$StaffApplyModel->region_name = implode(',', $apply_region_name);
					$result = $StaffApplyModel->save();
					if(false == $result){
						return $this->disposeJson(1, '保存数据失败');
					};
					
					return $this->disposeJson(0, '操作成功，即将刷新页面');
					
				// 处理结果
				case 'dispose_result' :
					
					$judge_1 = array_key_exists('result', $parameter) && is_bool($parameter['result']);
					if(!$judge_1){
						return $this->disposeJson(1, '参数校验失败');
					};
					
					$time = time();
					switch($parameter['result']){
						// 申请通过
						case true :
							
							\app\common\model\Model::startTrans();
							try{
								
								// 创建员工信息
								$StaffModel = new \app\common\model\StaffModel();
								$StaffModel->realname = $StaffApplyModel->realname;
								$StaffModel->phone = $StaffApplyModel->phone;
								$StaffModel->idcard_frontend = $StaffApplyModel->idcard_frontend;
								$StaffModel->idcard_backend = $StaffApplyModel->idcard_backend;
								$StaffModel->idcard_hold = $StaffApplyModel->idcard_hold;
								$StaffModel->create_time = $time;
								$StaffModel->is_disable = 0;
								$StaffModel->is_del = 0;
								$result = $StaffModel->save();
								if(false == $result){
									throw new \Exception('创建员工信息失败');
								};
								
								// 保存员工关联地址
								$region_list = array();
								$StaffRegionModel = new \app\common\model\StaffRegionModel();
								if(0 < mb_strlen($StaffApplyModel->region_id)){
									$region_id = explode(',', $StaffApplyModel->region_id);
									foreach($region_id as $id){
										$region_list[] = array(
											'staff_id' => $StaffModel->id,
											'region_id' => intval($id),
										);
									};
								};
								if(0 < count($region_list)){
									$result = $StaffRegionModel->saveAll($region_list);
									if(false == $result){
										throw new \Exception('保存员工关联地址失败');
									};
								};
								
								// 保存申请状态
								$StaffApplyModel->dispose_time = $time;
								$StaffApplyModel->result = 1;
								$result = $StaffApplyModel->save();
								if(false == $result){
									return $this->disposeJson(1, '保存申请状态失败');
								};
								
								// 修改用户状态
								$result = \app\common\model\SubscriberModel::where('id', $StaffApplyModel->subscriber_id)->where('staff_id', 0)->update([
									'staff_id' => $StaffModel->id
								]);
								if(false == $result){
									return $this->disposeJson(1, '修改用户状态失败');
								};
								
								\app\common\model\Model::commit();
								
							}catch(\Exception $error){
								
								\app\common\model\Model::rollback();
								$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
								return $this->disposeJson(1, $message);
								
							};
							
							return $this->disposeJson(0, '操作成功，即将刷新');
							
						// 申请拒绝
						case false;
							
							\app\common\model\Model::startTrans();
							try{
								
								// 保存申请处理时间
								$StaffApplyModel->dispose_time = $time;
								$result = $StaffApplyModel->save();
								if(false == $result){
									return $this->disposeJson(1, '保存数据失败');
								};
								
								// 保存申请状态
								$result = \app\common\model\StaffApplyModel::where('id', $StaffApplyModel->id)->where('result', 0)->update(['result' => 2]);
								if(1 !== $result){
									return $this->disposeJson(1, '保存申请状态失败');
								};
								
								\app\common\model\Model::commit();
								
							}catch(\Exception $error){
								
								\app\common\model\Model::rollback();
								$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
								return $this->disposeJson(1, $message);
								
							};
							
							return $this->disposeJson(0, '操作成功，即将刷新');
					};
					
				default:
					return $this->disposeJson(1, '调用的方法不存在');
			};
			
		}else{
			
			$view->assign('domain', \think\Config::get('application_domain'));
			
			$view->assign('apply', $StaffApplyModel->toArray());
			
			$apply_region = array();
			if(0 < mb_strlen($StaffApplyModel->region_name, 'utf8')){
				$apply_region = explode(',', $StaffApplyModel->region_name);
			};
			$view->assign('apply_region', $apply_region);
			
			return $view->fetch();
			
		};
		
	}
	
	/**
	 * 处理
	 */
	public function dispose() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		$judge_2 = array_key_exists('action', $parameter) && is_bool($parameter['action']);
		if(!$judge_1 || !$judge_2){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$StaffApplyModel = \app\common\model\StaffApplyModel::get($parameter['id']);
		if(null === $StaffApplyModel){
			return $this->disposeJson(1, '该申请未找到，请刷新后重试');
		}else if(0 !== $StaffApplyModel->result){
			return $this->disposeJson(1, '该申请已经被处理，请刷新后重试');
		};
		
		$SubscriberModel = \app\common\model\SubscriberModel::get($StaffApplyModel->subscriber_id);
		if(null === $SubscriberModel){
			return $this->disposeJson(1, '用户信息未找到，请重新登录');
		};
		
		$time = time();
		\app\common\model\Model::startTrans();
		try{
			
			// 保存申请信息
			$StaffApplyModel->result = (true === $parameter['action']) ? 1 : 2;
			$StaffApplyModel->dispose_time = $time;
			$result = $StaffApplyModel->save();
			if(false == $result){
				throw new \Exception('保存申请信息失败');
			};
			
			// 绑定用户
			if(0 === $SubscriberModel->staff_id){
				
				// 创建员工
				$StaffModel = new \app\common\model\StaffModel();
				$StaffModel->realname = $StaffApplyModel->realname;
				$StaffModel->phone = $StaffApplyModel->phone;
				$StaffModel->create_time = $time;
				$result = $StaffModel->save();
				if(false == $result){
					throw new \Exception('创建员工失败');
				};
				
				// 绑定到用户
				$SubscriberModel->staff_id = $StaffModel->id;
				$result = $SubscriberModel->save();
				if(false == $result){
					throw new \Exception('绑定到用户失败');
				};
			};
			
			// 操作完成
			\app\common\model\Model::commit();
			
		}catch(\Exception $error){
			
			\app\common\model\Model::rollback();
			$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
			return $this->disposeJson(1, $message);
			
		};
		
		return $this->disposeJson(0, '操作成功，即将刷新');
	}
}